package com.publish.file.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

public class FileUtils {
	public static Map<String, String> loadProperties(File file) {
		Map<String, String> properties = new HashMap<String, String>();
		FileReader fileReader = null;
		BufferedReader bufferedReader = null;
		try {
			fileReader = new FileReader(file);
			bufferedReader = new BufferedReader(fileReader);
			String lineString = null;
			do {
				lineString = bufferedReader.readLine();
				if (lineString != null) {
					String string = lineString.replaceAll(" ", "");
					String[] line = string.split("=");
					if (line.length == 2) {
						properties.put(line[0], line[1]);
					}
				}
			} while (lineString != null);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fileReader.close();
				bufferedReader.close();
			} catch (Exception e) {
			}
		}
		return properties;
	}

	/**
	 * @param size 文件大小转换成可视化字符串
	 * @return
	 */
	public static String getFormatSize(long size) {
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
		String wrongSize = "0B";
		if (size == 0) {
			return wrongSize;
		}
		if (size < 1024) {
			fileSizeString = df.format((double) size) + "B";
		} else if (size < 1048576) {
			fileSizeString = df.format((double) size / 1024) + "KB";
		} else if (size < 1073741824) {
			fileSizeString = df.format((double) size / 1048576) + "MB";
		} else {
			fileSizeString = df.format((double) size / 1073741824) + "GB";
		}
		return fileSizeString;
	}
}
